#include <string.h>
#include <stdlib.h>
#include "discountclientLoad.h"
int loadDiscountClients(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"r");
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;
	int numlines=getFileInfo(ptr_file,&maxlinelen);
	discountclientcount=numlines;
	discountclientdata=(struct DiscountClientVars*) calloc(numlines,sizeof(struct DiscountClientVars));
	char *buf=(char*) malloc(maxlinelen*sizeof(char));
	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);//load line into buffer;
		discountclientdata[i].clientid=(int)*strtok(buf,"/");//get first token from buffer
		strcpy(discountclientdata[i].discountid,strtok(NULL,"/"));//subsequent tokens...
		discountclientdata[i].startdate=(int)*strtok(NULL,"/");
		discountclientdata[i].expirydate=(int)*strtok(NULL,"/");
		discountclientdata[i].state=(int)*strtok(NULL,"/");
	}
	fclose(ptr_file);
	return 0;
}

int writeDiscountClients(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	for(int i=0;i<discountclientcount;i++){
		fprintf(ptr_file,"%d/%s/%d/%d/%d\n",discountclientdata[i].clientid,discountclientdata[i].discountid,discountclientdata[i].startdate,discountclientdata[i].expirydate,discountclientdata[i].state);
	}
	fclose(ptr_file);
	free(discountclientdata);
	return 0;
}

void addDiscountClient(struct DiscountClientVars n){
	discountclientdata=(struct DiscountClientVars*) realloc(discountclientdata,++discountclientcount*sizeof(struct DiscountClientVars));
	discountclientdata[discountclientcount-1]=n;
}

void rmDiscountClient(int index){
	for(int i=index;i<discountclientcount-1;i++){
		discountclientdata[i]=discountclientdata[i+1];
	}
	discountclientdata=(struct DiscountClientVars*) realloc(discountclientdata,--discountclientcount*sizeof(struct DiscountClientVars));
}
